package com.hexiang.rocketmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.acl.common.AclClientRPCHook;
import org.apache.rocketmq.acl.common.SessionCredentials;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.RPCHook;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Slf4j
@Component
public class DelayTimeMessageProducer {


    private DefaultMQProducer defaultMQProducer;

    private static final String TOPIC = "test_delay_time_topic";

    private String producerGroup = "delay_time_producer_group";

    private String nameServer = "127.0.0.1:9876";

    @PostConstruct
    public void start() throws MQClientException {
        defaultMQProducer = new DefaultMQProducer(producerGroup, getAclRPCHook());
        defaultMQProducer.setNamesrvAddr(nameServer);
        defaultMQProducer.start();
    }

    @PreDestroy
    public void shutdown() {
        defaultMQProducer.shutdown();
    }

    RPCHook getAclRPCHook() {
        return new AclClientRPCHook(new SessionCredentials("rocketmq_u1", "12345678"));
    }

    /**
     * 发送延时消息
     */
    public void sendDelayTimeMsg(String msgBody) {
        try {
            Message message = new Message(TOPIC, (msgBody).getBytes(RemotingHelper.DEFAULT_CHARSET));
            // 设置延时等级3,这个消息将在10s之后发送(现在只支持固定的几个时间,详看delayTimeLevel)
            message.setDelayTimeLevel(3);
            SendResult sendResult = defaultMQProducer.send(message);
            log.warn("sendResult={} ", sendResult);
        } catch (Exception e) {
            log.error("sendDelayTimeMsgErr,msgBody={}", msgBody, e);
        }

    }

}
